﻿// Copyright (c) MudBlazor 2021
// MudBlazor licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace MudBlazor.SourceGenerator;

internal static class SourceCodeBuilder
{
    private const string Identifier = "mudEnum";

    public static string Build(in EnumData enumData)
    {
        return $$"""
                 // Copyright (c) MudBlazor 2021
                 // MudBlazor licenses this file to you under the MIT license.
                 // See the LICENSE file in the project root for more information.

                 //----------------------
                 // <auto-generated>
                 // This code was auto generated by a source generator.
                 // </auto-generated>
                 //----------------------

                 // Disable obsolete warnings for generated code
                 #pragma warning disable CS0618

                 namespace {{enumData.Namespace}};

                 /// <summary>
                 /// Generated extension methods for <see cref="{{enumData.Name}}"/> enum.
                 /// </summary>
                 {{enumData.AccessModifier}} static class {{enumData.Classname}} {
                     
                     /// <summary>
                     /// Returns the value of the <see cref="System.ComponentModel.DescriptionAttribute"/> attribute.
                     /// If no description attribute was found the default ToString() method will be used.
                     /// </summary>
                     {{enumData.AccessModifier}} static string ToDescriptionString(this {{enumData.Name}} {{Identifier}})
                     {
                         return {{BuildSwitchExpression(in enumData)}}
                     }

                 }
                 """;
    }

    private static string BuildSwitchExpression(in EnumData enumData)
    {
        var builder = new StringBuilder();
        builder.AppendCode($"{Identifier} switch");
        builder.AppendCode("{", 2);
        foreach (var item in enumData.Members)
        {
            builder.AppendCode($"{enumData.Name}.{item.Value} => {item.Description},", 3);
        }

        builder.AppendCode($"_ => {Identifier}.ToString()", 3);

        builder.AppendCode("};", 2);
        return builder.ToString();
    }
}
